package com.view.myapplication.kotlin

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.view.myapplication.LogUtils
import com.view.myapplication.R
import com.view.myapplication.other.Job

class MainActivity : AppCompatActivity() {

    private val permissions: Array<String> = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.ACCESS_FINE_LOCATION
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun bt1(view: View) {
//        android.os.Process.killProcess(android.os.Process.myPid())
//        System.exit(0)
        Toast.makeText(this, "点击了ViewPager！！ ", Toast.LENGTH_SHORT).show()
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            requestPermissions(permissions, 100)
//        }
        if (!checkPermission(permissions)) {
            ActivityCompat.requestPermissions(
                this,
                permissions,
                100
            )
        }
    }

    fun btFunction(view: View) {
        /****************** 简化函数 ********************/
        val generateAnswerString = generateAnswerString(5, 2)
        LogUtils.i("generateAnswerString: $generateAnswerString")
        /****************** lambda 表达式和匿名函数 ********************/
        LogUtils.i("stringLengthFunc: " + stringLengthFunc("Happy ", "Birthday"))
        LogUtils.i("generateAnswerString3: " + generateAnswerString3(5, 3))
        funcNoParams()
        /****************** 高阶函数 ********************/
        stringMapper("Android", mapper)
        stringMapper(
            "ButAndroid"
        ) {
            val compareTo = it.compareTo("Android")
            LogUtils.i("$it compareTo Android is $compareTo")
            compareTo
        }
//        stringMapper("ButAndroid", { it -> it.compareTo("Android") })
//        stringMapper("ButAndroid") { it -> it.compareTo("Android") }
//        stringMapper("ButAndroid") { it.compareTo("Android") }
        stringMapper("Android13", ::mapper)
        // 函数作为返回值
        stringMapper("class start", stringMapperFunction(input = "class start xyz"))
        // 与 let 等函数的关系
        testLet()
        /****************** 扩展函数和扩展属性 ********************/
        val lastChar = "android".lastChar()
        LogUtils.i("android's lastChar: $lastChar")
        LogUtils.i("Smith's lastChar: ${"Smith".lastChar()}")
        //泛型扩展函数
        //与 apply 等函数的关系
        //扩展属性
        val listString = listOf("Android Q", "Android N", "Android M")
        LogUtils.i("listString.last${listString.last}")
        //与 KTX 的关系

        //伴生对象扩展函数和属性
        Job.print("Extension for Companion object.")
        /****************** 内联函数 ********************/
        highLevelFunction("Android") {
            it.length
        }
        /****************** 闭包 ********************/
        var sum = 0
        stringMapper("Android") {
            sum += it.length
            sum
        }
        LogUtils.i("闭包sum: $sum")
        /****************** 顶层函数 ********************/
        topFunction("Ellison")
        /****************** 局部函数 ********************/
        LogUtils.i("magic: ${magic()}")
        /****************** 运算符重载函数 ********************/
        val person1 = Person("A", 3)
        LogUtils.i("testInt+person1=${5 - person1}")
        //解构声明
        testDeco()
    }

    private fun testDeco() {
        val (msg, code) = Result("good", 1)
        LogUtils.i("msg:${msg} code:${code}")
    }

    inner class Result(
        private val msg: String,
        private val code: Int
    ) {
        operator fun component1() = msg
        operator fun component2() = code
    }

    data class Person(var name: String, var age: Int)

    operator fun Int.minus(p: Person) = this - p.age

    private fun magic(): Int {
        val v1 = (0..100).random()
        fun foo(): Int {
            return v1 * v1
        }
        return foo()
    }

    private inline fun highLevelFunction(input: String, mapper: (String) -> Int): Int {
        LogUtils.i("highLevelFunction input:$input")
        return mapper(input)
    }

    //简化函数
    private fun generateAnswerString(count: Int, countThreshold: Int): String {
        return if (count > countThreshold) {
            "I have the answer" + (count - countThreshold)
        } else {
            "The answer eludes me$count"
        }
    }

    private fun generateAnswerString2(count: Int, countThreshold: Int): String =
        if (count > countThreshold) {
            "I have the answer" + (count - countThreshold)
        } else {
            "The answer eludes me$count"
        }

    val generateAnswerString3: (Int, Int) -> String = { it1, it2 ->
        if (it1 > it2) {
            "I have the answer" + (it1 - it2)
        } else {
            "The answer eludes me$it1"
        }
    }

    //lambda 表达式和匿名函数
    val stringLengthFunc: (String, String) -> Int = { it, input ->
        val q: String = it + input
        q.length
    }

    private val funcNoParams: () -> Unit = {
        runOnUiThread {
            Toast.makeText(this, "function no params ", Toast.LENGTH_SHORT).show()
            LogUtils.i("function no params ")
        }
    }

    private fun stringMapperFunction(input: String): (String) -> Int {
        return {
            val newString = input.substring(input.indexOf("start"))
            val length = newString.length
            LogUtils.i("newString:$newString length:$length")
            length
        }
    }

    //高阶函数
    private fun stringMapper(input: String, mapper: (String) -> Int): Int {
        LogUtils.i("input: $input")
        return mapper(input)
    }


    private val mapper: (String) -> Int = { it ->
        val strLength = it.length
        LogUtils.i("$it ,长度为: $strLength")
        strLength
    }

    private fun mapper(input: String): Int {
        val length = input.length
        LogUtils.i("$input 长度为：$length")
        return length
    }

    private fun testLet() {
        val lastResult = stringMapper("Android", mapper).let { it ->
            "$it-done"
        }
        LogUtils.i("lastResult: $lastResult")

        tl(2, "kotlin function").let { i ->
            val i1 = i * 2
            LogUtils.i("kotlin function * 2: $i1")
            i1
        }
    }

    private fun tl(i: Int, s: String): Int {
        val i1 = s.length + i
        LogUtils.i("s: $s +$i ,it's length is $i1")
        return i1
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isEmpty()) return
        if (requestCode == 100) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "权限已获取", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "权限未获取", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun checkPermission(permissions: Array<String>): Boolean {
        for (i in 0..permissions.size) {
            val checkSelfPermission = ActivityCompat.checkSelfPermission(this, permissions[i])
            if (checkSelfPermission == PackageManager.PERMISSION_DENIED) {
                return false
            }
        }
        return true
    }

}

fun String.lastChar(): Char = this[length - 1]

val <T> List<T>.last: T get() = get(size - 1)

fun Job.Companion.print(summary: String) {
    LogUtils.i("Job:$summary")
}

fun topFunction(string: String) {
    LogUtils.i("this is top function for $string")
}








